package com.hanxiaozhang.sourcecode.executor;


import com.hanxiaozhang.sourcecode.aqs.MyAbstractQueuedSynchronizer;
import lombok.extern.slf4j.Slf4j;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * An {@link ExecutorService} that executes each submitted task using
 * one of possibly several pooled threads, normally configured
 * using {@link Executors} factory methods.
 *
 * <p>Thread pools address two different problems: they usually
 * provide improved performance when executing large numbers of
 * asynchronous tasks, due to reduced per-task invocation overhead,
 * and they provide a means of bounding and managing the resources,
 * including threads, consumed when executing a collection of tasks.
 * Each {@code ThreadPoolExecutor} also maintains some basic
 * statistics, such as the number of completed tasks.
 *
 * <p>To be useful across a wide range of contexts, this class
 * provides many adjustable parameters and extensibility
 * hooks. However, programmers are urged to use the more convenient
 * {@link Executors} factory methods {@link
 * Executors#newCachedThreadPool} (unbounded thread pool, with
 * automatic thread reclamation), {@link Executors#newFixedThreadPool}
 * (fixed size thread pool) and {@link
 * Executors#newSingleThreadExecutor} (single background thread), that
 * preconfigure settings for the most common usage
 * scenarios. Otherwise, use the following guide when manually
 * configuring and tuning this class:
 *
 * <dl>
 *
 * <dt>Core and maximum pool sizes</dt>
 *
 * <dd>A {@code ThreadPoolExecutor} will automatically adjust the
 * pool size (see {@link #getPoolSize})
 * according to the bounds set by
 * corePoolSize (see {@link #getCorePoolSize}) and
 * maximumPoolSize (see {@link #getMaximumPoolSize}).
 * <p>
 * When a new task is submitted in method {@link #execute(Runnable)},
 * and fewer than corePoolSize threads are running, a new thread is
 * created to handle the request, even if other worker threads are
 * idle.  If there are more than corePoolSize but less than
 * maximumPoolSize threads running, a new thread will be created only
 * if the queue is full.  By setting corePoolSize and maximumPoolSize
 * the same, you create a fixed-size thread pool. By setting
 * maximumPoolSize to an essentially unbounded value such as {@code
 * Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
 * number of concurrent tasks. Most typically, core and maximum pool
 * sizes are set only upon construction, but they may also be changed
 * dynamically using {@link #setCorePoolSize} and {@link
 * #setMaximumPoolSize}. </dd>
 *
 * <dt>On-demand construction</dt>
 *
 * <dd>By default, even core threads are initially created and
 * started only when new tasks arrive, but this can be overridden
 * dynamically using method {@link #prestartCoreThread} or {@link
 * #prestartAllCoreThreads}.  You probably want to prestart threads if
 * you construct the pool with a non-empty queue. </dd>
 *
 * <dt>Creating new threads</dt>
 *
 * <dd>New threads are created using a {@link ThreadFactory}.  If not
 * otherwise specified, a {@link Executors#defaultThreadFactory} is
 * used, that creates threads to all be in the same {@link
 * ThreadGroup} and with the same {@code NORM_PRIORITY} priority and
 * non-daemon status. By supplying a different ThreadFactory, you can
 * alter the thread's name, thread group, priority, daemon status,
 * etc. If a {@code ThreadFactory} fails to create a thread when asked
 * by returning null from {@code newThread}, the executor will
 * continue, but might not be able to execute any tasks. Threads
 * should possess the "modifyThread" {@code RuntimePermission}. If
 * worker threads or other threads using the pool do not possess this
 * permission, service may be degraded: configuration changes may not
 * take effect in a timely manner, and a shutdown pool may remain in a
 * state in which termination is possible but not completed.</dd>
 *
 * <dt>Keep-alive times</dt>
 *
 * <dd>If the pool currently has more than corePoolSize threads,
 * excess threads will be terminated if they have been idle for more
 * than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
 * This provides a means of reducing resource consumption when the
 * pool is not being actively used. If the pool becomes more active
 * later, new threads will be constructed. This parameter can also be
 * changed dynamically using method {@link #setKeepAliveTime(long,
 * TimeUnit)}.  Using a value of {@code Long.MAX_VALUE} {@link
 * TimeUnit#NANOSECONDS} effectively disables idle threads from ever
 * terminating prior to shut down. By default, the keep-alive policy
 * applies only when there are more than corePoolSize threads. But
 * method {@link #allowCoreThreadTimeOut(boolean)} can be used to
 * apply this time-out policy to core threads as well, so long as the
 * keepAliveTime value is non-zero. </dd>
 *
 * <dt>Queuing</dt>
 *
 * <dd>Any {@link BlockingQueue} may be used to transfer and hold
 * submitted tasks.  The use of this queue interacts with pool sizing:
 *
 * <ul>
 *
 * <li> If fewer than corePoolSize threads are running, the Executor
 * always prefers adding a new thread
 * rather than queuing.</li>
 *
 * <li> If corePoolSize or more threads are running, the Executor
 * always prefers queuing a request rather than adding a new
 * thread.</li>
 *
 * <li> If a request cannot be queued, a new thread is created unless
 * this would exceed maximumPoolSize, in which case, the task will be
 * rejected.</li>
 *
 * </ul>
 * <p>
 * There are three general strategies for queuing:
 * <ol>
 *
 * <li> <em> Direct handoffs.</em> A good default choice for a work
 * queue is a {@link SynchronousQueue} that hands off tasks to threads
 * without otherwise holding them. Here, an attempt to queue a task
 * will fail if no threads are immediately available to run it, so a
 * new thread will be constructed. This policy avoids lockups when
 * handling sets of requests that might have internal dependencies.
 * Direct handoffs generally require unbounded maximumPoolSizes to
 * avoid rejection of new submitted tasks. This in turn admits the
 * possibility of unbounded thread growth when commands continue to
 * arrive on average faster than they can be processed.  </li>
 *
 * <li><em> Unbounded queues.</em> Using an unbounded queue (for
 * example a {@link LinkedBlockingQueue} without a predefined
 * capacity) will cause new tasks to wait in the queue when all
 * corePoolSize threads are busy. Thus, no more than corePoolSize
 * threads will ever be created. (And the value of the maximumPoolSize
 * therefore doesn't have any effect.)  This may be appropriate when
 * each task is completely independent of others, so tasks cannot
 * affect each others execution; for example, in a web page server.
 * While this style of queuing can be useful in smoothing out
 * transient bursts of requests, it admits the possibility of
 * unbounded work queue growth when commands continue to arrive on
 * average faster than they can be processed.  </li>
 *
 * <li><em>Bounded queues.</em> A bounded queue (for example, an
 * {@link ArrayBlockingQueue}) helps prevent resource exhaustion when
 * used with finite maximumPoolSizes, but can be more difficult to
 * tune and control.  Queue sizes and maximum pool sizes may be traded
 * off for each other: Using large queues and small pools minimizes
 * CPU usage, OS resources, and context-switching overhead, but can
 * lead to artificially low throughput.  If tasks frequently block (for
 * example if they are I/O bound), a system may be able to schedule
 * time for more threads than you otherwise allow. Use of small queues
 * generally requires larger pool sizes, which keeps CPUs busier but
 * may encounter unacceptable scheduling overhead, which also
 * decreases throughput.  </li>
 *
 * </ol>
 *
 * </dd>
 *
 * <dt>Rejected tasks</dt>
 *
 * <dd>New tasks submitted in method {@link #execute(Runnable)} will be
 * <em>rejected</em> when the Executor has been shut down, and also when
 * the Executor uses finite bounds for both maximum threads and work queue
 * capacity, and is saturated.  In either case, the {@code execute} method
 * invokes the {@link
 * MyRejectedExecutionHandler#rejectedExecution(Runnable, MyThreadPoolExecutor)}
 * method of its {@link MyRejectedExecutionHandler}.  Four predefined handler
 * policies are provided:
 *
 * <ol>
 *
 * <li> In the default {@link MyThreadPoolExecutor.MyAbortPolicy}, the
 * handler throws a runtime {@link RejectedExecutionException} upon
 * rejection. </li>
 *
 * <li> In {@link MyThreadPoolExecutor.CallerRunsPolicy}, the thread
 * that invokes {@code execute} itself runs the task. This provides a
 * simple feedback control mechanism that will slow down the rate that
 * new tasks are submitted. </li>
 *
 * <li> In {@link MyThreadPoolExecutor.MyDiscardPolicy}, a task that
 * cannot be executed is simply dropped.  </li>
 *
 * <li>In {@link MyThreadPoolExecutor.MyDiscardOldestPolicy}, if the
 * executor is not shut down, the task at the head of the work queue
 * is dropped, and then execution is retried (which can fail again,
 * causing this to be repeated.) </li>
 *
 * </ol>
 * <p>
 * It is possible to define and use other kinds of {@link
 * MyRejectedExecutionHandler} classes. Doing so requires some care
 * especially when policies are designed to work only under particular
 * capacity or queuing policies. </dd>
 *
 * <dt>Hook methods</dt>
 *
 * <dd>This class provides {@code protected} overridable
 * {@link #beforeExecute(Thread, Runnable)} and
 * {@link #afterExecute(Runnable, Throwable)} methods that are called
 * before and after execution of each task.  These can be used to
 * manipulate the execution environment; for example, reinitializing
 * ThreadLocals, gathering statistics, or adding log entries.
 * Additionally, method {@link #terminated} can be overridden to perform
 * any special processing that needs to be done once the Executor has
 * fully terminated.
 *
 * <p>If hook or callback methods throw exceptions, internal worker
 * threads may in turn fail and abruptly terminate.</dd>
 *
 * <dt>Queue maintenance</dt>
 *
 * <dd>Method {@link #getQueue()} allows access to the work queue
 * for purposes of monitoring and debugging.  Use of this method for
 * any other purpose is strongly discouraged.  Two supplied methods,
 * {@link #remove(Runnable)} and {@link #purge} are available to
 * assist in storage reclamation when large numbers of queued tasks
 * become cancelled.</dd>
 *
 * <dt>Finalization</dt>
 *
 * <dd>A pool that is no longer referenced in a program <em>AND</em>
 * has no remaining threads will be {@code shutdown} automatically. If
 * you would like to ensure that unreferenced pools are reclaimed even
 * if users forget to call {@link #shutdown}, then you must arrange
 * that unused threads eventually die, by setting appropriate
 * keep-alive times, using a lower bound of zero core threads and/or
 * setting {@link #allowCoreThreadTimeOut(boolean)}.  </dd>
 *
 * </dl>
 *
 * <p><b>Extension example</b>. Most extensions of this class
 * override one or more of the protected hook methods. For example,
 * here is a subclass that adds a simple pause/resume feature:
 *
 * <pre> {@code
 * class PausableThreadPoolExecutor extends ThreadPoolExecutor {
 *   private boolean isPaused;
 *   private ReentrantLock pauseLock = new ReentrantLock();
 *   private Condition unpaused = pauseLock.newCondition();
 *
 *   public PausableThreadPoolExecutor(...) { super(...); }
 *
 *   protected void beforeExecute(Thread t, Runnable r) {
 *     super.beforeExecute(t, r);
 *     pauseLock.lock();
 *     try {
 *       while (isPaused) unpaused.await();
 *     } catch (InterruptedException ie) {
 *       t.interrupt();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void pause() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = true;
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 *
 *   public void resume() {
 *     pauseLock.lock();
 *     try {
 *       isPaused = false;
 *       unpaused.signalAll();
 *     } finally {
 *       pauseLock.unlock();
 *     }
 *   }
 * }}</pre>
 *
 * @author Doug Lea
 * @since 1.5
 */

/**
 * 功能描述: <br>
 * 〈ThreadPoolExecutor 源码〉
 *
 * @Author:hanxinghua
 * @Date: 2021/11/30
 */
@Slf4j
public class MyThreadPoolExecutor extends AbstractExecutorService {

    /**
     * The main pool control state, ctl, is an atomic integer packing two conceptual fields workerCount,
     * indicating the effective number of threads. runState, indicating whether running, shutting down etc
     * <p>
     * 线程池控制状态的叫ctl，它是一个Integer原子数，它包含workerCount(有效线程数)和runState(运行状态，运行，关闭等)两个部分
     * <p>
     * In order to pack them into one int, we limit workerCount to
     * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2 billion) otherwise representable.
     * If this is ever an issue in the future, the variable can be changed to be an AtomicLong,
     * and the shift/mask constants below adjusted. But until the need arises,
     * this code is a bit faster and simpler using an int.
     * <p>
     * 为了将它们打包成一个int，我们将workerCount限制为（2^29）-1（约5亿）个线程，而不是（2^31）-1（20亿）个可表示的线程。
     * 如果这在将来成为问题，可以将变量更改为原子长度，并调整下面的移位/掩码常数。但在需要之前，此代码使用int更快更简单。
     * <p>
     * The workerCount is the number of workers that have been permitted to start and not permitted to stop.
     * The value may be transiently different from the actual number of live threads,
     * for example when a ThreadFactory fails to create a thread when asked,
     * and when exiting threads are still performing bookkeeping before terminating.
     * The user-visible pool size is reported as the current size of the workers set.
     * <p>
     * workerCount是允许启动和不允许停止的线程数量。
     * 该值可能暂时不同于活动线程的实际数量，例如，当ThreadFactory在请求时未能创建线程；
     * 在退出时线程在终止前仍在执行。用户可见池大小，显示为当前工作集的大小。
     * <p>
     * <p>
     * The runState provides the main lifecycle control, taking on values:
     * runState提供主要的生命周期控制，具有以下值：
     * <p>
     * RUNNING(运行中):接受新任务并处理排队的任务
     * Accept new tasks and process queued tasks
     * <p>
     * SHUTDOWN(关闭):不接受新任务，但处理排队的任务
     * Don't accept new tasks, but process queued tasks
     * <p>
     * STOP(停止):不接受新任务、不处理排队的任务和中断正在进行的任务
     * Don't accept new tasks, don't process queued tasks, and interrupt in-progress tasks
     * <p>
     * TIDYING(整理):所有任务都已终止，workerCount为零，转换到状态TIDING的线程将运行terminated()钩子方法
     * All tasks have terminated, workerCount is zero, the thread transitioning to state TIDYING
     * will run the terminated() hook method
     * <p>
     * TERMINATED(结束): terminated()已完成
     * terminated() has completed
     * <p>
     * <p>
     * The numerical order among these values matters, to allow ordered comparisons.
     * The runState monotonically increases over time, but need not hit each state. The transitions are:
     * <p>
     * 这些值之间的数字顺序很重要，以便进行有序比较。 runState随时间单调增加，但不需要达到每个状态。过渡是:
     * <p>
     * RUNNING -> SHUTDOWN ：在调用shutdown()时，可能隐式地在finalize()中
     * On invocation of shutdown(), perhaps implicitly in finalize()
     * <p>
     * (RUNNING or SHUTDOWN) -> STOP ：在调用shutdownNow()时
     * On invocation of shutdownNow()
     * <p>
     * SHUTDOWN -> TIDYING ：当队列和池都为空时
     * When both queue and pool are empty
     * <p>
     * STOP -> TIDYING ：当池为空时
     * When pool is empty
     * <p>
     * TIDYING -> TERMINATED ：当调用terminated()钩子方法完成时
     * When the terminated() hook method has completed
     * <p>
     * <p>
     * Threads waiting in awaitTermination() will return when the state reaches TERMINATED.
     * 在awaitTermination()中等待的线程将在状态达到TERMINATED时返回
     * <p>
     * Detecting the transition from SHUTDOWN to TIDYING is less straightforward than you'd like
     * because the queue may become empty after non-empty and vice versa during SHUTDOWN state,
     * but we can only terminate if, after seeing that it is empty,
     * we see that workerCount is 0 (which sometimes entails a recheck -- see below).
     * <p>
     * 检测从关闭(SHUTDOWN)到清理(TIDYING)的转换并不像您希望的那样简单，因为队列在非空状态下可能变为空，
     * 在关机(SHUTDOWN)状态下也可能变为空，但我们只能在看到workerCount为空后，看到workerCount为0时终止
     * （这有时需要重新检查——见下文）
     */
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    // 计数位，32-3=29位
    private static final int COUNT_BITS = Integer.SIZE - 3;
    // 线程的容量：（2^29）-1（约5亿）个线程
    // 0001 1111 1111 1111 1111 1111 1111 1111
    private static final int CAPACITY = (1 << COUNT_BITS) - 1;

    // runState存储在高阶位中 runState is stored in the high-order bits
    // 1110 0000 0000 0000 0000 0000 0000 0000
    private static final int RUNNING = -1 << COUNT_BITS;
    // 0000 0000 0000 0000 0000 0000 0000 0000
    private static final int SHUTDOWN = 0 << COUNT_BITS;
    // 0010 0000 0000 0000 0000 0000 0000 0000
    private static final int STOP = 1 << COUNT_BITS;
    // 0100 0000 0000 0000 0000 0000 0000 0000
    private static final int TIDYING = 2 << COUNT_BITS;
    // 0110 0000 0000 0000 0000 0000 0000 0000
    private static final int TERMINATED = 3 << COUNT_BITS;

    // 封装和拆分ctl Packing and unpacking ctl
    private static int runStateOf(int c) {
        return c & ~CAPACITY;
    }

    private static int workerCountOf(int c) {
        return c & CAPACITY;
    }

    private static int ctlOf(int rs, int wc) {
        return rs | wc;
    }

    /*
     * Bit field accessors that don't require unpacking ctl.
     * These depend on the bit layout and on workerCount being never negative.
     *
     * 不需要拆分ctl的位字段访问器。这取决于位布局和workerCount从不为负。
     */

    /*
     *状态c是否小于s
     */
    private static boolean runStateLessThan(int c, int s) {
        return c < s;
    }

    /*
     *状态c是否大于等于s
     */
    private static boolean runStateAtLeast(int c, int s) {
        return c >= s;
    }

    /**
     * 状态c是否为RUNNING
     *
     * @param c
     * @return
     */
    private static boolean isRunning(int c) {
        return c < SHUTDOWN;
    }

    /**
     * Attempts to CAS-increment the workerCount field of ctl.
     * <p>
     * CAS增加一个有效的线程
     */
    private boolean compareAndIncrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect + 1);
    }

    /**
     * Attempts to CAS-decrement the workerCount field of ctl.
     * <p>
     * CAS减少一个有效的线程
     */
    private boolean compareAndDecrementWorkerCount(int expect) {
        return ctl.compareAndSet(expect, expect - 1);
    }

    /**
     * Decrements the workerCount field of ctl. This is called only on
     * abrupt termination of a thread (see processWorkerExit). Other
     * decrements are performed within getTask.
     * <p>
     * 自旋递减workerCount。这仅在线程突然终止时调用（请参阅processWorkerExit）。其他减量在getTask中执行。
     */
    private void decrementWorkerCount() {
        do {
        } while (!compareAndDecrementWorkerCount(ctl.get()));
    }

    /**
     * The queue used for holding tasks and handing off to worker threads.
     * We do not require that workQueue.poll() returning null necessarily means that workQueue.isEmpty(),
     * so rely solely on isEmpty to see if the queue is empty
     * (which we must do for example when deciding whether to transition from SHUTDOWN to TIDYING).
     * This accommodates special-purpose queues such as DelayQueues for which poll() is allowed to
     * return null even if it may later return non-null when delays expire.
     * <p>
     * 用于保存任务并将其传递给工作线程的队列。
     * <p>
     * 我们不要求workQueue.poll()返回null，必然需要使用workQueue.isEmpty()，因此，仅依靠isEmpty()来查看队列是否为空。
     * （例如，在决定是否从SHUTDOWN --> TIDYING时，我们必须这样做）。这适用于特殊用途的队列，例如允许poll()返回null的DelayQueues，
     * 即使延迟过期后poll()可能返回非null。
     */
    private final BlockingQueue<Runnable> workQueue;

    /**
     * Lock held on access to workers set and related bookkeeping.
     * While we could use a concurrent set of some sort, it turns out to be generally preferable to use a lock.
     * Among the reasons is that this serializes interruptIdleWorkers, which avoids unnecessary interrupt storms,
     * especially during shutdown.
     * Otherwise exiting threads would concurrently interrupt those that have not yet interrupted.
     * It also simplifies some of the associated statistics bookkeeping of largestPoolSize etc.
     * We also hold mainLock on shutdown and shutdownNow, for the sake of ensuring workers set
     * is stable while separately checking permission to interrupt and actually interrupting.
     * <p>
     * 锁定workers set和related bookkeeping的访问权限。
     * 虽然我们可以使用某种类型的并发集，但通常最好使用锁。其中一个原因是，它序列化了中断Workers，从而避免了不必要的中断风暴，
     * 尤其是在关机期间。否则，退出的线程将同时中断那些尚未中断的线程。
     * 它还简化了一些与最大池大小等相关的统计簿记。
     * 我们还在关机和关机时保持mainLock，以确保workers set稳定，同时分别检查中断和实际中断的权限。
     */
    private final ReentrantLock mainLock = new ReentrantLock();

    /**
     * Set containing all worker threads in pool. Accessed only when holding mainLock.
     * <p>
     * 包含池中所有工作线程的集合。仅在持有mainLock时访问，即加锁的时候访问，HashSet线程不安全。
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();

    /**
     * Wait condition to support awaitTermination
     * <p>
     * 等待条件支持等待终止
     */
    private final Condition termination = mainLock.newCondition();

    /**
     * Tracks largest attained pool size. Accessed only under mainLock.
     * <p>
     * 跟踪达到的最大池大小。仅在mainLock下访问，即加锁的时候访问。
     */
    private int largestPoolSize;

    /**
     * Counter for completed tasks. Updated only on termination of worker threads. Accessed only under mainLock.
     * <p>
     * 已完成任务的计数器。仅在工作线程终止时更新。仅在mainLock下访问，即加锁的时候访问。
     */
    private long completedTaskCount;

    /*
     * All user control parameters are declared as volatiles so that ongoing actions are based on freshest values,
     * but without need for locking,since no internal invariants depend on them changing synchronously
     * with respect to other actions.
     * <p>
     * 所有用户控件参数都声明为volatile，因此正在进行的操作都基于最新的值，
     * 但不需要锁定，因为没有内部不变量依赖于它们相对于其他操作的同步更改。
     */

    /**
     * Factory for new threads. All threads are created using this factory (via method addWorker).
     * All callers must be prepared for addWorker to fail, which may reflect a system or user's
     * policy limiting the number of threads.
     * Even though it is not treated as an error, failure to create threads may result in
     * new tasks being rejected or existing ones remaining stuck in the queue.
     * We go further and preserve pool invariants even in the face of errors such as OutOfMemoryError,
     * that might be thrown while trying to create threads.
     * Such errors are rather common due to the need to allocate a native stack in Thread.start,
     * and users will want to perform clean pool shutdown to clean up.
     * There will likely be enough memory available for the cleanup code to
     * complete without encountering yet another OutOfMemoryError.
     * <p>
     * 新线程的工厂。所有线程都是使用此工厂创建的（通过addWorker方法）。
     * 所有调用者都必须为addWorker失败做好准备，这可能反映了系统或用户限制线程数量的策略。
     * 即使未将其视为错误，创建线程的失败也可能会导致新任务被拒绝，或现有任务仍然卡在队列中。
     * 我们更进一步，保留池不变量，即使在遇到错误时，例如OutOfMemoryError，也会在尝试创建线程时抛出。
     * 由于需要在Thread.start中分配本机堆栈，因此此类错误非常常见，用户将希望执行清理池关闭以清理。
     * 可能会有足够的内存供清理代码完成，而不会遇到另一个OutOfMemoryError。
     */
    private volatile ThreadFactory threadFactory;

    /**
     * Handler called when saturated or shutdown in execute.
     * <p>
     * 在execute中饱和或关闭时调用处理程序。
     */
    private volatile MyRejectedExecutionHandler handler;

    /**
     * Timeout in nanoseconds for idle threads waiting for work.
     * Threads use this timeout when there are more than corePoolSize present or if allowCoreThreadTimeOut.
     * Otherwise they wait forever for new work.
     * <p>
     * 空闲线程等待工作的超时（纳秒）
     * 当存在超过corePoolSize的线程或allowCoreThreadTimeOut时，线程使用此超时。否则，他们将永远等待新的工作
     * <p>
     */
    private volatile long keepAliveTime;

    /**
     * If false (default), core threads stay alive even when idle.
     * If true, core threads use keepAliveTime to time out waiting for work.
     * <p>
     * 是否允许核心线程超时。
     * 如果为false（默认），则核心线程即使在空闲时也保持活动状态。
     * 如果为true，则核心线程使用keepAliveTime超时等待工作。
     */
    private volatile boolean allowCoreThreadTimeOut;

    /**
     * Core pool size is the minimum number of workers to keep alive (and not allow to time out etc)
     * unless allowCoreThreadTimeOut is set, in which case the minimum is zero.
     * <p>
     * 核心线程数是保持活动状态的最小工作线程数（不允许超时等），除非设置了allowCoreThreadTimeOut，
     * 在这种情况下，最小值为零。
     */
    private volatile int corePoolSize;

    /**
     * Maximum pool size. Note that the actual maximum is internally bounded by CAPACITY.
     * <p>
     * 最大池大小。请注意，实际最大值在内部由容量限制。
     */
    private volatile int maximumPoolSize;

    /**
     * The default rejected execution handler
     * <p>
     * 默认被拒绝的执行处理程序
     */
    private static final MyRejectedExecutionHandler defaultHandler =
            new MyAbortPolicy();

    /**
     * Permission required for callers of shutdown and shutdownNow.
     * We additionally require (see checkShutdownAccess) that callers have permission to actually interrupt
     * threads in the worker set (as governed by Thread.interrupt, which relies on ThreadGroup.checkAccess,
     * which in turn relies on SecurityManager.checkAccess).
     * Shutdowns are attempted only if these checks pass.
     * <p>
     * shutdown和shutdownNow调用方所需的权限
     * 此外，我们还要求（请参阅checkShutdownAccess）调用方有权实际中断工作程序集中的个线程（由Thread.interrupt控制，它依赖于ThreadGroup.checkAccess，
     * 反过来又依赖于SecurityManager.checkAccess）。
     * 仅当这些检查通过时才尝试关闭。
     * <p>
     * All actual invocations of Thread.interrupt (see interruptIdleWorkers and interruptWorkers)
     * ignore SecurityExceptions, meaning that the attempted interrupts silently fail.
     * In the case of shutdown, they should not fail unless the SecurityManager has inconsistent policies,
     * sometimes allowing access to a thread and sometimes not. In such cases,
     * failure to actually interrupt threads may disable or delay full termination.
     * Other uses of interruptIdleWorkers are advisory, and failure to actually interrupt will merely delay response to
     * configuration changes so is not handled exceptionally.
     */
    private static final RuntimePermission shutdownPerm = new RuntimePermission("modifyThread");


    /*
     *  The context to be used when executing the finalizer, or null.
     *  <p>
     *  执行终结器时要使用的上下文，或null。
     */
    private final AccessControlContext acc;

    /**
     * Class Worker mainly maintains interrupt control state for threads running tasks,
     * along with other minor bookkeeping.
     * This class opportunistically extends AbstractQueuedSynchronizer to simplify acquiring
     * and releasing a lock surrounding each task execution.
     * This protects against interrupts that are intended to wake up a worker thread waiting for
     * a task from instead interrupting a task being run.
     * We implement a simple non-reentrant mutual exclusion lock rather than use ReentrantLock
     * because we do not want worker tasks to be able to reacquire the lock
     * when they invoke pool control methods like setCorePoolSize.
     * Additionally, to suppress interrupts until the thread actually starts running tasks,
     * we initialize lock state to a negative value, and clear it upon start (in runWorker).
     * <p>
     * Worker主要维护运行任务的线程的中断控制状态，以及其他次要簿记。
     * 此类选择性地扩展AbstractQueuedSynchronizer，以简化获取和释放围绕每个任务执行的锁。
     * 这可以防止旨在唤醒等待任务的工作线程，而不是中断正在运行的任务的中断。
     * 我们实现了一个简单的不可重入的互斥锁。不使用可重入锁原因：我们不希望工作任务再被调用。
     * 例如，setCorePoolSize之类的池控制方法是可以重新获取锁。
     * 此外，为了在线程实际开始运行任务之前抑制中断，我们将锁状态初始化为负值，并在启动时清除它（在runWorker中）。
     */
    private final class Worker extends MyAbstractQueuedSynchronizer implements Runnable {

        /**
         * This class will never be serialized, but we provide a serialVersionUID to suppress a javac warning.
         * <p>
         * 这个类永远不会被序列化，但我们提供了serialVersionUID来抑制javac警告
         */
        private static final long serialVersionUID = 6138294804551838833L;

        /**
         * Thread this worker is running in.  Null if factory fails.
         * <p>
         * 此工作线程正在运行。如果工厂失败，则为Null。
         */
        final Thread thread;

        /**
         * Initial task to run.  Possibly null.
         * <p>
         * 要运行的初始任务。可能是null。
         */
        Runnable firstTask;

        /**
         * Per-thread task counter
         * <p>
         * 每线程任务计数器
         */
        volatile long completedTasks;

        /**
         * Creates with given first task and thread from ThreadFactory.
         * <p>
         * 使用ThreadFactory中给定的第一个任务和线程创建。
         *
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
            // 在运行Worker之前禁止中断 inhibit interrupts until runWorker
            // // TODO: 2021/11/29 抑制中断为什么要把state设置成-1
            setState(-1);
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /**
         * Delegates main run loop to outer runWorker
         * <p>
         * 将主运行循环委托给外部runWorker
         */
        @Override
        public void run() {
            runWorker(this);
        }

        // Lock methods 锁定方法 值0表示解锁状态。值1表示锁定状态。
        // The value 0 represents the unlocked state.
        // The value 1 represents the locked state.

        /**
         * 是否是独占方式
         *
         * @return
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() != 0;
        }

        /**
         * 尝试获取
         *
         * @param unused
         * @return
         */
        @Override
        protected boolean tryAcquire(int unused) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 尝试释放
         *
         * @param unused
         * @return
         */
        @Override
        protected boolean tryRelease(int unused) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        /**
         * 加锁
         */
        public void lock() {
            acquire(1);
        }

        /**
         * 尝试加锁
         *
         * @return
         */
        public boolean tryLock() {
            return tryAcquire(1);
        }

        /**
         * 解锁
         */
        public void unlock() {
            release(1);
        }

        /**
         * 是否获取锁
         *
         * @return
         */
        public boolean isLocked() {
            return isHeldExclusively();
        }

        /**
         * 启动时中断 ??
         */
        void interruptIfStarted() {
            Thread t;
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
    }

    /*
     * Methods for setting control state 设置控制状态的方法
     */

    /**
     * Transitions runState to given target, or leaves it alone if already at least the given target.
     * <p>
     * 将运行状态转换到给定的目标，或者至少在给定的目标上保留运行状态。
     *
     * @param targetState the desired state, either SHUTDOWN or STOP
     *                    (but not TIDYING or TERMINATED -- use tryTerminate for that)
     */
    private void advanceRunState(int targetState) {
        for (; ; ) {
            int c = ctl.get();
            if (runStateAtLeast(c, targetState) || ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c)))) {
                break;
            }
        }
    }

    /**
     * Transitions to TERMINATED state if either (SHUTDOWN and pool and queue empty) or (STOP and pool empty).
     * If otherwise eligible to terminate but workerCount is nonzero,
     * interrupts an idle worker to ensure that shutdown signals propagate.
     * This method must be called following any action that might make termination possible
     * -- reducing worker count or removing tasks from the queue during shutdown.
     * The method is non-private to allow access from ScheduledThreadPoolExecutor.
     * <p>
     * 如果任何一个是 SHUTDOWN状态并且池和队列为空 或 STOP状态且池为空，则转换为TERMINATED状态。
     * 如果有资格终止，但workerCount不为零，将中断空闲工作进程，以确保停机信号传播。
     * 在执行任何可能导致终止的操作之后，必须调用此方法——在关闭期间减少worker计数或从队列中删除任务。
     * 该方法是非私有的，允许从ScheduledThreadPoolExecutor进行访问。
     */
    final void tryTerminate() {
        for (; ; ) {
            int c = ctl.get();
            // isRunning(c) 当前线程池是运行状态 ||
            // runStateAtLeast(c, TIDYING) 当前线程池是整理或终止状态 ||
            // runStateOf(c) == SHUTDOWN && !workQueue.isEmpty() 当先线程池是关闭状态但是，队列不为空
            // 以上三种状态结束尝试终止
            if (isRunning(c) || runStateAtLeast(c, TIDYING) ||
                    (runStateOf(c) == SHUTDOWN && !workQueue.isEmpty())) {
                return;
            }
            // Eligible to terminate 有资格终止
            // 有效线程不为0,将中断一个空闲的worker
            if (workerCountOf(c) != 0) {
                interruptIdleWorkers(ONLY_ONE);
                return;
            }
            // 加锁修改
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                // CAS将ctl的TIDYING + 0
                if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
                    try {
                        // 调用终止方法
                        terminated();
                    } finally {
                        // 最后设置为 TERMINATED + 0
                        ctl.set(ctlOf(TERMINATED, 0));
                        // 通知所有的锁等待
                        termination.signalAll();
                    }
                    return;
                }
            } finally {
                mainLock.unlock();
            }
            // else retry on failed CAS 否则，请在失败的CA上重试
        }
    }

    /*
     * Methods for controlling interrupts to worker threads. 控制工作线程中断的方法
     */

    /**
     * If there is a security manager, makes sure caller has permission
     * to shut down threads in general (see shutdownPerm).
     * If this passes, additionally makes sure the caller is allowed to interrupt each worker thread.
     * This might not be true even if first check passed, if the SecurityManager treats some threads specially.
     * <p>
     * 如果有安全管理器，请确保调用者具有关闭线程的权限（请参阅shutdownPerm）。
     * 如果通过，则另外确保允许调用方中断每个工作线程。
     * 如果SecurityManager特别处理某些线程，则即使第一次检查通过，这也可能不是真的。
     */
    private void checkShutdownAccess() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkPermission(shutdownPerm);
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                for (Worker w : workers) {
                    security.checkAccess(w.thread);
                }
            } finally {
                mainLock.unlock();
            }
        }
    }

    /**
     * Interrupts all threads, even if active.
     * Ignores SecurityExceptions(in which case some threads may remain uninterrupted).
     * <p>
     * 中断所有线程，即使处于活动状态。忽略SecurityExceptions（在这种情况下，某些线程可能会保持不间断）。
     */
    private void interruptWorkers() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers) {
                w.interruptIfStarted();
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Interrupts threads that might be waiting for tasks (as indicated by not being locked)
     * so they can check for termination or configuration changes.
     * Ignores SecurityExceptions (in which case some threads may remain uninterrupted).
     * <p>
     * 中断可能正在等待任务的线程（如未锁定所示），以便它们可以检查终止或配置更改。
     * 忽略SecurityExceptions（在这种情况下，某些线程可能会保持不间断）。
     *
     * @param onlyOne If true, interrupt at most one worker. This is
     *                called only from tryTerminate when termination is otherwise
     *                enabled but there are still other workers.  In this case, at
     *                most one waiting worker is interrupted to propagate shutdown
     *                signals in case all threads are currently waiting.
     *                Interrupting any arbitrary thread ensures that newly arriving
     *                workers since shutdown began will also eventually exit.
     *                To guarantee eventual termination, it suffices to always
     *                interrupt only one idle worker, but shutdown() interrupts all
     *                idle workers so that redundant workers exit promptly, not
     *                waiting for a straggler task to finish.
     */
    private void interruptIdleWorkers(boolean onlyOne) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (Worker w : workers) {
                Thread t = w.thread;
                if (!t.isInterrupted() && w.tryLock()) {
                    try {
                        t.interrupt();
                    } catch (SecurityException ignore) {
                    } finally {
                        w.unlock();
                    }
                }
                if (onlyOne) {
                    break;
                }
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Common form of interruptIdleWorkers, to avoid having to remember
     * what the boolean argument means.
     * <p>
     * 常见的中断形式，以避免必须记住布尔参数的含义。
     */
    private void interruptIdleWorkers() {
        interruptIdleWorkers(false);
    }

    private static final boolean ONLY_ONE = true;

    /*
     * Misc utilities, most of which are also exported to ScheduledThreadPoolExecutor
     *<p>
     * Misc实用程序，其中大多数还导出到ScheduledThreadPoolExecutor
     */

    /**
     * Invokes the rejected execution handler for the given command.
     * Package-protected for use by ScheduledThreadPoolExecutor.
     * <p>
     * 为给定命令调用被拒绝的执行处理程序。
     * 受ScheduledThreadPoolExecutor保护的包。
     */
    final void reject(Runnable command) {
        handler.rejectedExecution(command, this);
    }

    /**
     * Performs any further cleanup following run state transition on invocation of shutdown.
     * A no-op here, but used by ScheduledThreadPoolExecutor to cancel delayed tasks.
     * <p>
     * 调用shutdown时执行运行状态转换后的任何进一步清理。
     * 此处为无操作，但ScheduledThreadPoolExecutor用于取消延迟的任务。
     */
    void onShutdown() {
    }

    /**
     * State check needed by ScheduledThreadPoolExecutor to enable running tasks during shutdown.
     * <p>
     * ScheduledThreadPoolExecutor在关机期间启用正在运行的任务所需的状态检查
     *
     * @param shutdownOK true if should return true if SHUTDOWN
     */
    final boolean isRunningOrShutdown(boolean shutdownOK) {
        int rs = runStateOf(ctl.get());
        return rs == RUNNING || (rs == SHUTDOWN && shutdownOK);
    }

    /**
     * Drains the task queue into a new list, normally using drainTo.
     * But if the queue is a DelayQueue or any other kind of queue for
     * which poll or drainTo may fail to remove some elements, it deletes them one by one.
     * <p>
     * 通常使用drainTo将任务队列排入新列表。
     * 但如果队列是DelayQueue或任何其他类型的队列，轮询或drainTo可能无法删除某些元素，则会逐个删除它们。
     */
    private List<Runnable> drainQueue() {
        BlockingQueue<Runnable> q = workQueue;
        ArrayList<Runnable> taskList = new ArrayList<Runnable>();
        q.drainTo(taskList);
        if (!q.isEmpty()) {
            for (Runnable r : q.toArray(new Runnable[0])) {
                if (q.remove(r)) {
                    taskList.add(r);
                }
            }
        }
        return taskList;
    }

    /*
     * Methods for creating, running and cleaning up after workers  workers的创建、运行和清理方法
     */

    /**
     * Checks if a new worker can be added with respect to current pool state and the given bound
     * (either core or maximum).
     * If so, the worker count is adjusted accordingly, and, if possible,
     * a new worker is created and started, running firstTask as its first task.
     * This method returns false if the pool is stopped or eligible to shut down.
     * It also returns false if the thread factory fails to create a thread when asked.
     * If the thread creation fails, either due to the thread factory returning null,
     * or due to an exception (typically OutOfMemoryError in Thread.start()), we roll back cleanly.
     * <p>
     * 检查是否可以根据当前池状态和给定的绑定核心或最大值添加新的worker。
     * 如果是这样，则会相应地调整工作进程计数，如果可能的话，将创建并启动一个新的工作进程，并将firstTask作为其第一个任务运行。
     * 如果池已停止或符合关闭条件，则此方法返回false。如果线程工厂在被询问时未能创建线程，则返回false。
     * 如果线程创建失败，或者是由于线程工厂返回null，或者是由于异常（通常是thread.start()中的OutOfMemoryError），
     * 我们将完全回滚。
     * <p>
     * 添加worker
     *
     * @param firstTask the task the new thread should run first (or
     *                  null if none). Workers are created with an initial first task
     *                  (in method execute()) to bypass queuing when there are fewer
     *                  than corePoolSize threads (in which case we always start one),
     *                  or when the queue is full (in which case we must bypass queue).
     *                  Initially idle threads are usually created via
     *                  prestartCoreThread or to replace other dying workers.
     * @param core      if true use corePoolSize as bound, else maximumPoolSize.
     *                  如果为true，则使用corePoolSize作为绑定，否则使用maximumPoolSize。
     *                  (A boolean indicator is used here rather than a value to ensure reads of
     *                  fresh values after checking other pool state).
     * @return true if successful
     */
    private boolean addWorker(Runnable firstTask, boolean core) {
        // 这个循环，增加有效线程数（wc）
        retry:
        for (; ; ) {

            int c = ctl.get();
            int rs = runStateOf(c);

            // 仅在必要时检查队列是否为空。
            // rs 大于等于 SHUTDOWN 即 大于等于0，runState可能是 shutdown(0)、stop(1)、tidying(2)、terminate(3)
            // !(rs是SHUTDOWN并且提交任务为空并且workQueue不为空)
            if (rs >= SHUTDOWN &&
                    !(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty())) {
                return false;
            }
            /*
            可以往下进行的情况：
            i.rs是running状态；
            ii.rs是shutdown状态,提交为空,但工作队列不为空
             */

            for (; ; ) {
                // 有效线程数
                int wc = workerCountOf(c);
                // 有效线程数大于等于容量 || 有效线程数大于核心线程数（最大线程数）
                if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) {
                    return false;
                }
                //  使用CAS将workerCount+1, 修改成功则跳到外层循环，结束
                if (compareAndIncrementWorkerCount(c)) {
                    break retry;
                }
                // 重读ctl
                c = ctl.get();
                // 当前的runState 不等于上面获取的调跳到外层循环，重新开始循环内层
                if (runStateOf(c) != rs) {
                    continue retry;
                }

                // 其他CAS由于workerCount更改而失败；重试内部循环
            }
        }

        // Worker的线程是否启动标识
        boolean workerStarted = false;
        // Worker的线程是否添加标识
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 创建一个work
            w = new Worker(firstTask);
            final Thread t = w.thread;
            // 线程不为空
            if (t != null) {
                // 加锁
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    // Recheck while holding lock.  在保持锁定的同时重新检查。
                    // Back out on ThreadFactory failure or if shut down before lock acquired.
                    // 在ThreadFactory出现故障或在获取锁之前关闭时退出。

                    int rs = runStateOf(ctl.get());
                    // rs是运行状态 || rs是SHUTDOWN并且firstTask为空的情况
                    if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
                        // 如果当前线程处于活跃状态，抛异常
                        if (t.isAlive()) {
                            // precheck that t is startable 预先检查t是否可启动
                            throw new IllegalThreadStateException();
                        }
                        // 添加到workers
                        workers.add(w);
                        // 修改largestPoolSize
                        int s = workers.size();
                        if (s > largestPoolSize) {
                            largestPoolSize = s;
                        }
                        // 设置workerAdded
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                // worker添加成功，启动线程，设置workerStarted状态
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            // 线程启动失败时，调用addWorkerFailed()
            if (!workerStarted) {
                addWorkerFailed(w);
            }
        }
        // 返回worker是否启动成功
        return workerStarted;
    }

    /**
     * Rolls back the worker thread creation.
     * - removes worker from workers, if present
     * - decrements worker count
     * - rechecks for termination, in case the existence of this worker was holding up termination
     * <p>
     * 回滚工作线程创建：
     * - 如果存在，从workers中移除worker
     * - 减少工作人员计数
     * - 重新检查是否可以终止，以防该worker不能终止
     */
    private void addWorkerFailed(Worker w) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            if (w != null) {
                workers.remove(w);
            }
            decrementWorkerCount();
            tryTerminate();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Performs cleanup and bookkeeping for a dying worker. Called only from worker threads.
     * Unless completedAbruptly is set, assumes that workerCount has already been adjusted to account for exit.
     * This method removes thread from worker set, and possibly terminates the pool or replaces the worker if either
     * it exited due to user task exception or if fewer than corePoolSize workers are running or queue is non-empty but
     * there are no workers.
     * <p>
     * 为垂死的工人进行清理和记账。仅从工作线程调用。
     * 除非设置了completedAbruptly，否则假定workerCount已被调整以考虑退出。
     * 如果线程由于用户任务异常而退出，或者如果正在运行的工作线程少于corePoolSize，或者队列为非空但没有工作线程，
     * 则此方法从工作线程集中删除线程，并可能终止池或替换工作线程。
     *
     * @param w                 the worker
     * @param completedAbruptly if the worker died due to user exception
     */
    private void processWorkerExit(Worker w, boolean completedAbruptly) {
        // completedAbruptly为true，wc减一
        if (completedAbruptly) {
            decrementWorkerCount();
        }
        // 加锁处理completedTaskCount和从workers中移除
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            completedTaskCount += w.completedTasks;
            workers.remove(w);
        } finally {
            mainLock.unlock();
        }
        // 尝试终止
        tryTerminate();

        int c = ctl.get();
        // runState是running或shutdown
        if (runStateLessThan(c, STOP)) {
            // worker正常结束
            if (!completedAbruptly) {
                // 获取最小线程数
                int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
                // min等于0，但是工作队列不为空，把min设置成1
                if (min == 0 && !workQueue.isEmpty()) {
                    min = 1;
                }
                // 当前有效的线程数大于等于min，直接返回
                if (workerCountOf(c) >= min) {
                    return; // replacement not needed 不需要更换
                }
            }
            // 添加一个worker ？？
            addWorker(null, false);
        }
    }

    /**
     * Performs blocking or timed wait for a task, depending on current configuration settings,
     * or returns null if this worker must exit because of any of:
     * 1. There are more than maximumPoolSize workers (due to a call to setMaximumPoolSize).
     * 2. The pool is stopped.
     * 3. The pool is shutdown and the queue is empty.
     * 4. This worker timed out waiting for a task, and timed-out workers are subject to termination
     * (that is, {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
     * both before and after the timed wait, and if the queue is non-empty,
     * this worker is not the last thread in the pool.
     * <p>
     * 根据当前的配置设置，对任务执行阻塞或定时等待，如果由于以下原因必须退出此工作进程，则返回null：
     * 1.有超过maximumPoolSize工作线程（由于调用了setMaximumPoolSize）。
     * 2.池已停止。
     * 3.池已关闭，队列为空。
     * 4.此工作线程在等待任务时超时，超时工作线程在超时等待前后都会终止，即allowCoreThreadTimeOut
     * 或者workerCount>corePoolSize，如果队列非空，此工作线程不是池中的最后一个线程。
     *
     * @return task, or null if the worker must exit, in which case
     * workerCount is decremented
     */
    private Runnable getTask() {
        // Did the last poll() time out?   上次poll()超时了吗？
        boolean timedOut = false;

        for (; ; ) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary. 仅在必要时检查队列是否为空。
            // rs是stop或tidying或terminate 并且workQueue为空，wc减一，返回获取任务为空
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            // Are workers subject to culling? workers会被淘汰吗？
            // timed 是 允许核心超时 或者 当前有效线程数量大于核心线程数量
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
            // (有效线程数量大于最大线程数量 || timed && timedOut) &&
            //  (wc > 1 || workQueue.isEmpty())
            if ((wc > maximumPoolSize || (timed && timedOut))
                    && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c)) {
                    return null;
                }
                continue;
            }

            try {
                // 获取任务
                Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take();
                if (r != null) {
                    return r;
                }
                // r为空，获取当前任务超时
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }


    /**
     * Main worker run loop.  Repeatedly gets tasks from queue and executes them,
     * while coping with a number of issues:
     * 主工作运行循环。重复从队列中获取任务并执行它们，同时处理许多问题：
     * <p>
     * 1. We may start out with an initial task, in which case we don't need to get the first one.
     * Otherwise, as long as pool is running, we get tasks from getTask.
     * If it returns null then the worker exits due to changed pool state or configuration parameters.
     * Other exits result from exception throws in external code, in which case completedAbruptly holds,
     * which usually leads processWorkerExit to replace this thread.
     * 1. 我们可以从初始任务开始，在这种情况下，我们不需要获得第一个任务。其他的只要池正在运行，我们就可以从getTask获得任务。
     * 如果返回null，则worker将由于池状态或配置参数的更改而退出。其他退出源于外部代码中的异常抛出，
     * 在这种情况下completedAbruptly保持不变，这通常会导致processWorkerExit替换此线程。
     * <p>
     * 2. Before running any task, the lock is acquired to prevent other pool interrupts
     * while the task is executing, and then we ensure that unless pool is stopping,
     * this thread does not have its interrupt set.
     * 2.在运行任何任务之前，获取锁是为了防止任务执行时，发生其他池中断，然后我们确保除非池停止时，
     * 此线程没有中断设置。
     * <p>
     * 3. Each task run is preceded by a call to beforeExecute, which might throw an exception,
     * in which case we cause thread to die (breaking loop with completedAbruptly true)
     * without processing the task.
     * 3.每个任务运行之前都会调用beforeExecute，这可能会引发异常，在这种情况下，会导致线程在不处理任务的情况下死亡。
     * （跳出循环在completedAbruptly为true）
     * <p>
     * 4. Assuming beforeExecute completes normally, we run the task, gathering any of
     * its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the specs guarantee that we trap)
     * and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run,
     * we wrap them within Errors on the way out (to the thread's UncaughtExceptionHandler).
     * Any thrown exception also conservatively causes thread to die.
     * 4.假设beforeExecute正常完成，我们运行任务，收集其抛出的任何异常以发送给afterExecute。我们分别处理RuntimeException、
     * Error（这两个规范都保证我们可以捕获）和任意丢弃。因为我们不能在Runnable.run中重新抛出丢弃的文件，所以我们在退出时，
     * 将它们包装在UncaughtExceptionHandler错误中。任何抛出的异常也会保守地导致线程死亡。
     * <p>
     * 5. After task.run completes, we call afterExecute, which may also throw an exception,
     * which will also cause thread to die. According to JLS Sec 14.20,
     * this exception is the one that will be in effect even if task.run throws.
     * 5.在task.run完成后，我们调用afterExecute，这也可能引发异常，这也会导致线程死亡。根据JLS第14.20节，
     * 即使task.run抛出，此异常也将生效。
     * <p>
     * The net effect of the exception mechanics is that afterExecute and the thread's
     * UncaughtExceptionHandler have as accurate information as we can provide about
     * any problems encountered by user code.
     * 异常机制的最终效果是afterExecute和线程的UncaughtExceptionHandler具有尽可能精确的信息，
     * 我们可以提供用户代码遇到的任何问题。
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        // 获取当前线程
        Thread wt = Thread.currentThread();
        // 获取worker上的任务
        Runnable task = w.firstTask;
        w.firstTask = null;

        w.unlock(); // allow interrupts  允许中断
        // 突然完成，即不正常的任务结束
        boolean completedAbruptly = true;
        try {
            // 循环获取任务
            while (task != null || (task = getTask()) != null) {
                // 加锁
                w.lock();
                // If pool is stopping, ensure thread is interrupted; if not, ensure thread is not interrupted.
                // This requires a recheck in second case to deal with shutdownNow race while clearing interrupt
                // 如果线程池正在停止，请确保线程已中断；如果没有，请确保线程没有中断。
                // 这需要在第二种情况下进行重新检查，以在清除中断的同时处理shutdownNow的竞争

                //  当前的运行状态为stop、tidying、terminate ||
                //  当前线程设置为中断 并且 当前的运行状态为stop、tidying、terminate 并且 !wt.isInterrupted() ?? 没看懂这里 2021-12-01
                if ((runStateAtLeast(ctl.get(), STOP) ||
                        (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) {
                    // 设置中断标识
                    wt.interrupt();
                }
                try {
                    // 调用beforeExecute
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        // 执行任务
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x;
                        throw x;
                    } catch (Error x) {
                        thrown = x;
                        throw x;
                    } catch (Throwable x) {
                        thrown = x;
                        throw new Error(x);
                    } finally {
                        // 调用afterExecute
                        afterExecute(task, thrown);
                    }
                } finally {
                    // 清除任务
                    task = null;
                    // 完成数加一
                    w.completedTasks++;
                    w.unlock();
                }
            }
            // 任务正常结束
            completedAbruptly = false;
        } finally {
            // 调用Worker退出
            processWorkerExit(w, completedAbruptly);
        }
    }

    // Public constructors and methods 公共建构者与方法

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory and rejected execution handler.
     * It may be more convenient to use one of the {@link Executors} factory
     * methods instead of this general purpose constructor.
     *
     * @param corePoolSize    the number of threads to keep in the pool, even
     *                        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *                        pool
     * @param keepAliveTime   when the number of threads is greater than the core,
     *                        this is the maximum time that excess idle threads
     *                        will wait for new tasks before terminating.
     *                        当线程数大于核心时，这是多余空闲线程在终止前等待新任务的最长时间
     * @param unit            the time unit for the {@code keepAliveTime} argument
     * @param workQueue       the queue to use for holding tasks before they are
     *                        executed.  This queue will hold only the {@code Runnable}
     *                        tasks submitted by the {@code execute} method.
     * @throws IllegalArgumentException if one of the following holds:<br>
     *                                  {@code corePoolSize < 0}<br>
     *                                  {@code keepAliveTime < 0}<br>
     *                                  {@code maximumPoolSize <= 0}<br>
     *                                  {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException     if {@code workQueue} is null
     */
    public MyThreadPoolExecutor(int corePoolSize,
                                int maximumPoolSize,
                                long keepAliveTime,
                                TimeUnit unit,
                                BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
                Executors.defaultThreadFactory(), defaultHandler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default rejected execution handler.
     *
     * @param corePoolSize    the number of threads to keep in the pool, even
     *                        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *                        pool
     * @param keepAliveTime   when the number of threads is greater than
     *                        the core, this is the maximum time that excess idle threads
     *                        will wait for new tasks before terminating.
     * @param unit            the time unit for the {@code keepAliveTime} argument
     * @param workQueue       the queue to use for holding tasks before they are
     *                        executed.  This queue will hold only the {@code Runnable}
     *                        tasks submitted by the {@code execute} method.
     * @param threadFactory   the factory to use when the executor
     *                        creates a new thread
     * @throws IllegalArgumentException if one of the following holds:<br>
     *                                  {@code corePoolSize < 0}<br>
     *                                  {@code keepAliveTime < 0}<br>
     *                                  {@code maximumPoolSize <= 0}<br>
     *                                  {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException     if {@code workQueue}
     *                                  or {@code threadFactory} is null
     */
    public MyThreadPoolExecutor(int corePoolSize,
                                int maximumPoolSize,
                                long keepAliveTime,
                                TimeUnit unit,
                                BlockingQueue<Runnable> workQueue,
                                ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
                threadFactory, defaultHandler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters and default thread factory.
     *
     * @param corePoolSize    the number of threads to keep in the pool, even
     *                        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *                        pool
     * @param keepAliveTime   when the number of threads is greater than
     *                        the core, this is the maximum time that excess idle threads
     *                        will wait for new tasks before terminating.
     * @param unit            the time unit for the {@code keepAliveTime} argument
     * @param workQueue       the queue to use for holding tasks before they are
     *                        executed.  This queue will hold only the {@code Runnable}
     *                        tasks submitted by the {@code execute} method.
     * @param handler         the handler to use when execution is blocked
     *                        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *                                  {@code corePoolSize < 0}<br>
     *                                  {@code keepAliveTime < 0}<br>
     *                                  {@code maximumPoolSize <= 0}<br>
     *                                  {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException     if {@code workQueue}
     *                                  or {@code handler} is null
     */
    public MyThreadPoolExecutor(int corePoolSize,
                                int maximumPoolSize,
                                long keepAliveTime,
                                TimeUnit unit,
                                BlockingQueue<Runnable> workQueue,
                                MyRejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
                Executors.defaultThreadFactory(), handler);
    }

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize    the number of threads to keep in the pool, even
     *                        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *                        pool
     * @param keepAliveTime   when the number of threads is greater than
     *                        the core, this is the maximum time that excess idle threads
     *                        will wait for new tasks before terminating.
     * @param unit            the time unit for the {@code keepAliveTime} argument
     * @param workQueue       the queue to use for holding tasks before they are
     *                        executed.  This queue will hold only the {@code Runnable}
     *                        tasks submitted by the {@code execute} method.
     * @param threadFactory   the factory to use when the executor
     *                        creates a new thread
     * @param handler         the handler to use when execution is blocked
     *                        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *                                  {@code corePoolSize < 0}<br>
     *                                  {@code keepAliveTime < 0}<br>
     *                                  {@code maximumPoolSize <= 0}<br>
     *                                  {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException     if {@code workQueue}
     *                                  or {@code threadFactory} or {@code handler} is null
     */
    public MyThreadPoolExecutor(int corePoolSize,
                                int maximumPoolSize,
                                long keepAliveTime,
                                TimeUnit unit,
                                BlockingQueue<Runnable> workQueue,
                                ThreadFactory threadFactory,
                                MyRejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
                maximumPoolSize <= 0 ||
                maximumPoolSize < corePoolSize ||
                keepAliveTime < 0) {
            throw new IllegalArgumentException();
        }
        if (workQueue == null || threadFactory == null || handler == null) {
            throw new NullPointerException();
        }
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

    /**
     * Executes the given task sometime in the future.
     * The task may execute in a new thread or in an existing pooled thread.
     * <p>
     * 在将来的某个时候执行给定的任务。任务可以在新线程或现有池线程中执行。
     * <p>
     * If the task cannot be submitted for execution, either because this executor has been shutdown
     * or because its capacity has been reached,the task is handled by the current
     * {@code MyRejectedExecutionHandler}.
     * <p>
     * 如果由于此执行器已关闭或已达到其容量而无法提交任务执行，
     * 则该任务将由当前{@code MyRejectedExecutionHandler}处理
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *                                    {@code MyRejectedExecutionHandler}, if the task
     *                                    cannot be accepted for execution
     * @throws NullPointerException       if {@code command} is null
     */
    @Override
    public void execute(Runnable command) {
        if (command == null) {
            throw new NullPointerException();
        }
        /*
         * Proceed in 3 steps:
         * 分三步进行：
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first task.
         * The call to addWorker atomically checks runState and workerCount,
         * and so prevents false alarms that would add threads when it shouldn't,
         * by returning false.
         * 1.如果运行的线程少于corePoolSize，请尝试以给定命令作为第一个任务启动新线程。
         * 对addWorker的调用以原子方式检查运行状态和workerCount，从而通过返回false来防止错误警报，
         * 从而在不应该添加线程时添加线程。
         * <p>
         * 2. If a task can be successfully queued, then we still need to double-check
         * whether we should have added a thread (because existing ones died since last checking)
         * or that the pool shut down since entry into this method.
         * So we recheck state and if necessary roll back the enqueuing if stopped,
         * or start a new thread if there are none.
         * 2.如果任务可以成功排队，那么我们仍然需要仔细检查是否应该添加线程（因为自上次检查以来已有线程已死亡）
         * 或者自进入此方法后池已关闭。
         * <p>
         * 3. If we cannot queue task, then we try to add a new thread.
         * If it fails, we know we are shut down or saturated and so reject the task.
         * 3.如果无法对任务排队，则尝试添加新线程。如果失败了，我们知道我们已经被关闭或饱和，因此拒绝该任务。
         */
        // 获取当前的ctl
        int c = ctl.get();
        // 如果当前线程数小于核心线程数，添加worker
        if (workerCountOf(c) < corePoolSize) {
            // addWorker(command, true)：创建核心线程
            if (addWorker(command, true)) {
                return;
            }
            c = ctl.get();
        }
        // 如果当前线程处于运行状态，并且任务插入工作队列成功
        if (isRunning(c) && workQueue.offer(command)) {
            // 再次获取状态
            int recheck = ctl.get();
            // 再次检测，线程池不是运行状态，调用remove(command)，即从队列中删除任务
            if (!isRunning(recheck) && remove(command)) {
                // 调用拒绝策略
                reject(command);
                // 再次检测，是运行状态，并且有效的线程数为0
            } else if (workerCountOf(recheck) == 0) {
                // 添加一个新Worker，即创建一个新线程
                addWorker(null, false);
            }
            // 当前线程处于运行状态，工作队列插入失败，即工作队列满了，尝试添加一个Worker
            // 如果添加失败，调用决绝策略
        } else if (!addWorker(command, false)) {
            reject(command);
        }
    }

    /**
     * Initiates an orderly shutdown in which previously submitted tasks are executed,
     * but no new tasks will be accepted. Invocation has no additional effect if already shut down.
     * <p>
     * 启动有序关机，执行以前提交的任务，但不接受新任务。如果调用已经关闭，则调用没有其他效果。
     * <p>
     * This method does not wait for previously submitted tasks to complete execution.
     * Use {@link #awaitTermination awaitTermination} to do that.
     * <p>
     * 此方法不会等待以前提交的任务完成执行。使用link.awaitTermination()完成此操作。
     *
     * @throws SecurityException {@inheritDoc}
     */
    @Override
    public void shutdown() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(SHUTDOWN);
            interruptIdleWorkers();
            onShutdown(); // hook for ScheduledThreadPoolExecutor
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
    }

    /**
     * Attempts to stop all actively executing tasks, halts the processing of waiting tasks,
     * and returns a list of the tasks that were awaiting execution.
     * These tasks are drained (removed) from the task queue upon return from this method.
     * <p>
     * 尝试停止所有正在执行的任务，停止正在等待的任务的处理，并返回正在等待执行的任务的列表。
     * 从该方法返回时，这些任务将从任务队列中排出（删除）
     * <p>
     * This method does not wait for actively executing tasks to terminate.
     * Use {@link #awaitTermination awaitTermination} to do that.
     * 此方法不会等待以前提交的任务完成执行。使用link.awaitTermination()完成此操作。
     * <p>
     * There are no guarantees beyond best-effort attempts to stop processing actively executing tasks.
     * This implementation cancels tasks via {@link Thread#interrupt}, so any task that fails to respond
     * to interrupts may never terminate.
     * <p>
     * 除了尽最大努力尝试停止处理积极执行的任务之外，没有其他保证。
     * 此实现通过Thread.interrupt()取消任务，因此任何未能响应中断的任务可能永远不会终止。
     *
     * @throws SecurityException {@inheritDoc}
     */
    @Override
    public List<Runnable> shutdownNow() {
        List<Runnable> tasks;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            checkShutdownAccess();
            advanceRunState(STOP);
            interruptWorkers();
            tasks = drainQueue();
        } finally {
            mainLock.unlock();
        }
        tryTerminate();
        return tasks;
    }

    /**
     * 是否关机
     *
     * @return
     */
    @Override
    public boolean isShutdown() {
        return !isRunning(ctl.get());
    }

    /**
     * Returns true if this executor is in the process of terminating after {@link #shutdown} or
     * {@link #shutdownNow} but has not completely terminated. This method may be useful for debugging.
     * A return of {@code true} reported a sufficient period after shutdown may indicate that submitted
     * tasks have ignored or suppressed interruption, causing this executor not to properly terminate.
     * <p>
     * 如果此执行器在shutdown()或shutdownNow()之后正在终止，但尚未完全终止，则返回true。
     * 此方法可能对调试有用。在关机后足够长的时间内返回true可能表示提交的任务忽略或抑制了中断，
     * 导致此执行器无法正确终止。
     *
     * @return {@code true} if terminating but not yet terminated
     */
    public boolean isTerminating() {
        int c = ctl.get();
        return !isRunning(c) && runStateLessThan(c, TERMINATED);
    }

    /**
     * 判断是否已经终止
     *
     * @return
     */
    @Override
    public boolean isTerminated() {
        return runStateAtLeast(ctl.get(), TERMINATED);
    }

    /**
     * 等待终止
     *
     * @param timeout
     * @param unit
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit)
            throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            for (; ; ) {
                if (runStateAtLeast(ctl.get(), TERMINATED)) {
                    return true;
                }
                if (nanos <= 0) {
                    return false;
                }
                nanos = termination.awaitNanos(nanos);
            }
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Invokes {@code shutdown} when this executor is no longer referenced and it has no threads.
     * <p>
     * 当此执行器不再被引用且没有线程时调用shutdown()。
     */
    @Override
    protected void finalize() {
        SecurityManager sm = System.getSecurityManager();
        if (sm == null || acc == null) {
            shutdown();
        } else {
            PrivilegedAction<Void> pa = () -> {
                shutdown();
                return null;
            };
            AccessController.doPrivileged(pa, acc);
        }
    }

    /**
     * Sets the thread factory used to create new threads.
     * <p>
     * 设置用于创建新线程的线程工厂
     *
     * @param threadFactory the new thread factory
     * @throws NullPointerException if threadFactory is null
     * @see #getThreadFactory
     */
    public void setThreadFactory(ThreadFactory threadFactory) {
        if (threadFactory == null) {
            throw new NullPointerException();
        }
        this.threadFactory = threadFactory;
    }

    /**
     * Returns the thread factory used to create new threads.
     * <p>
     * 返回用于创建新线程的线程工厂
     *
     * @return the current thread factory
     * @see #setThreadFactory(ThreadFactory)
     */
    public ThreadFactory getThreadFactory() {
        return threadFactory;
    }

    /**
     * Sets a new handler for unexecutable tasks.
     * <p>
     * 设置RejectedExecutionHandler
     *
     * @param handler the new handler
     * @throws NullPointerException if handler is null
     * @see #getMyRejectedExecutionHandler
     */
    public void setMyRejectedExecutionHandler(MyRejectedExecutionHandler handler) {
        if (handler == null) {
            throw new NullPointerException();
        }
        this.handler = handler;
    }

    /**
     * Returns the current handler for unexecutable tasks.
     * <p>
     * 获取RejectedExecutionHandler
     *
     * @return the current handler
     * @see #setMyRejectedExecutionHandler(MyRejectedExecutionHandler)
     */
    public MyRejectedExecutionHandler getMyRejectedExecutionHandler() {
        return handler;
    }

    /**
     * Sets the core number of threads.  This overrides any value set in the constructor.
     * If the new value is smaller than the current value,
     * excess existing threads will be terminated when they next become idle.
     * If larger, new threads will, if needed, be started to execute any queued tasks.
     * <p>
     * 设置核心线程数。这将覆盖构造函数中设置的任何值。如果新值小于当前值，多余的现有线程将在下次空闲时终止。
     * 如果较大，如果需要，将启动新线程以执行任何排队的任务。
     *
     * @param corePoolSize the new core size
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     * @see #getCorePoolSize
     */
    public void setCorePoolSize(int corePoolSize) {
        if (corePoolSize < 0) {
            throw new IllegalArgumentException();
        }
        int delta = corePoolSize - this.corePoolSize;
        this.corePoolSize = corePoolSize;
        if (workerCountOf(ctl.get()) > corePoolSize) {
            interruptIdleWorkers();
        } else if (delta > 0) {
            // We don't really know how many new threads are "needed".
            // As a heuristic, prestart enough new workers (up to new
            // core size) to handle the current number of tasks in
            // queue, but stop if queue becomes empty while doing so.
            int k = Math.min(delta, workQueue.size());
            while (k-- > 0 && addWorker(null, true)) {
                if (workQueue.isEmpty()) {
                    break;
                }
            }
        }
    }

    /**
     * Returns the core number of threads.
     * <p>
     * 获取核心线程数
     *
     * @return the core number of threads
     * @see #setCorePoolSize
     */
    public int getCorePoolSize() {
        return corePoolSize;
    }

    /**
     * Starts a core thread, causing it to idly wait for work.
     * This overrides the default policy of starting core threads only when new tasks are executed.
     * This method will return {@code false} if all core threads have already been started.
     * <p>
     * 启动核心线程，使其空闲等待工作。这将覆盖仅在执行新任务时启动核心线程的默认策略。
     * 如果所有核心线程都已启动，此方法将返回false。
     *
     * @return {@code true} if a thread was started
     */
    public boolean prestartCoreThread() {
        return workerCountOf(ctl.get()) < corePoolSize &&
                addWorker(null, true);
    }

    /**
     * Same as prestartCoreThread except arranges that at least one thread is started
     * even if corePoolSize is 0.
     * <p>
     * 与prestartCoreThread相同，只是安排至少启动一个线程，即使corePoolSize为0
     */
    void ensurePrestart() {
        int wc = workerCountOf(ctl.get());
        if (wc < corePoolSize) {
            addWorker(null, true);
        } else if (wc == 0) {
            addWorker(null, false);
        }
    }

    /**
     * Starts all core threads, causing them to idly wait for work.
     * This overrides the default policy of starting core threads only when
     * new tasks are executed.
     * <p>
     * 启动所有核心线程，使其空闲等待工作。
     * 这将覆盖仅在执行新任务时启动核心线程的默认策略。
     *
     * @return the number of threads started
     */
    public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true)) {
            ++n;
        }
        return n;
    }

    /**
     * Returns true if this pool allows core threads to time out and terminate if no tasks
     * arrive within the keepAlive time, being replaced if needed when new tasks arrive.
     * When true, the same keep-alive policy applying to non-core threads applies also to core threads.
     * When false (the default), core threads are never terminated due to lack of incoming tasks.
     * <p>
     * 如果此池允许核心线程超时，并在keepAlive时间内没有任务到达时终止，则返回true，如果新任务到达时需要替换。
     * 如果为true，则应用于非核心线程的相同保持活动策略也适用于核心线程。
     * 如果为false（默认值），则不会由于缺少传入任务而终止核心线程。
     *
     * @return {@code true} if core threads are allowed to time out, else {@code false}
     * @since 1.6
     */
    public boolean allowsCoreThreadTimeOut() {
        return allowCoreThreadTimeOut;
    }

    /**
     * Sets the policy governing whether core threads may time out and terminate
     * if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.
     * When false, core threads are never terminated due to lack of incoming tasks.
     * When true,the same keep-alive policy applying to non-core threads applies also to core threads.
     * To avoid continual thread replacement, the keep-alive time must be greater than zero when setting {@code true}.
     * This method should in general be called before the pool is actively used.
     * <p>
     * 设置控制核心线程是否可能超时和终止的策略，如果在"保持活动"时间内没有任务到达，则在新任务到达时根据需要进行更换。
     * 如果为false，则不会因为缺少传入任务而终止核心线程。如果为true，则应用于非核心线程的相同"保持活动"策略也适用于核心线程。
     *
     * @param value {@code true} if should time out, else {@code false}
     * @throws IllegalArgumentException if value is {@code true}
     *                                  and the current keep-alive time is not greater than zero
     * @since 1.6
     */
    public void allowCoreThreadTimeOut(boolean value) {
        if (value && keepAliveTime <= 0) {
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        }
        if (value != allowCoreThreadTimeOut) {
            allowCoreThreadTimeOut = value;
            if (value) {
                interruptIdleWorkers();
            }
        }
    }

    /**
     * Sets the maximum allowed number of threads. This overrides any value set in the constructor.
     * If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle.
     * <p>
     * 设置允许的最大线程数。这将覆盖构造函数中设置的任何值。如果新值小于当前值，则多余的现有线程将在下次空闲时终止
     *
     * @param maximumPoolSize the new maximum
     * @throws IllegalArgumentException if the new maximum is
     *                                  less than or equal to zero, or
     *                                  less than the {@linkplain #getCorePoolSize core pool size}
     * @see #getMaximumPoolSize
     */
    public void setMaximumPoolSize(int maximumPoolSize) {
        if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize) {
            throw new IllegalArgumentException();
        }
        this.maximumPoolSize = maximumPoolSize;
        if (workerCountOf(ctl.get()) > maximumPoolSize) {
            interruptIdleWorkers();
        }
    }

    /**
     * Returns the maximum allowed number of threads.
     * <p>
     * 获取MaximumPoolSize
     *
     * @return the maximum allowed number of threads
     * @see #setMaximumPoolSize
     */
    public int getMaximumPoolSize() {
        return maximumPoolSize;
    }

    /**
     * Sets the time limit for which threads may remain idle before being terminated.
     * If there are more than the core number of threads currently in the pool,
     * after waiting this amount of time without processing a task, excess threads will be terminated.
     * This overrides any value set in the constructor.
     * <p>
     * 设置线程在终止之前可以保持空闲的时间限制。如果池中当前的线程数超过核心线程数，在等待这段时间而不处理任务后，
     * 多余的线程将被终止。这将覆盖构造函数中设置的任何值。
     *
     * @param time the time to wait.  A time value of zero will cause
     *             excess threads to terminate immediately after executing tasks.
     * @param unit the time unit of the {@code time} argument
     * @throws IllegalArgumentException if {@code time} less than zero or
     *                                  if {@code time} is zero and {@code allowsCoreThreadTimeOut}
     * @see #getKeepAliveTime(TimeUnit)
     */
    public void setKeepAliveTime(long time, TimeUnit unit) {
        if (time < 0) {
            throw new IllegalArgumentException();
        }
        if (time == 0 && allowsCoreThreadTimeOut()) {
            throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
        }
        long keepAliveTime = unit.toNanos(time);
        long delta = keepAliveTime - this.keepAliveTime;
        this.keepAliveTime = keepAliveTime;
        if (delta < 0) {
            interruptIdleWorkers();
        }
    }

    /**
     * Returns the thread keep-alive time, which is the amount of time
     * that threads in excess of the core pool size may remain idle before being terminated.
     * <p>
     * 返回线程保持活动时间，即超过核心池大小的线程在终止前可能保持空闲的时间量。
     *
     * @param unit the desired time unit of the result
     * @return the time limit
     * @see #setKeepAliveTime(long, TimeUnit)
     */
    public long getKeepAliveTime(TimeUnit unit) {
        return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
    }

    // User-level queue utilities  用户级队列实用程序

    /**
     * Returns the task queue used by this executor.
     * Access to the task queue is intended primarily for debugging and monitoring.
     * This queue may be in active use.
     * Retrieving the task queue does not prevent queued tasks from executing.
     * <p>
     * 返回此执行器使用的任务队列。
     * 对任务队列的访问主要用于调试和监视。
     * 此队列可能正在使用中。
     * 检索任务队列不会阻止执行排队的任务。
     *
     * @return the task queue
     */
    public BlockingQueue<Runnable> getQueue() {
        return workQueue;
    }

    /**
     * Removes this task from the executor's internal queue if it is present,
     * thus causing it not to be run if it has not already started.
     * <p>
     * 如果存在此任务，则从执行器的内部队列中删除该任务，从而导致尚未启动的任务无法运行。
     * <p>
     * This method may be useful as one part of a cancellation scheme.
     * It may fail to remove tasks that have been converted into other forms before being placed on the internal queue.
     * For example, a task entered using {@code submit} might be converted into a form that maintains {@code Future} status.
     * However, in such cases, method {@link #purge} may be used to remove those Futures that have been cancelled.
     * <p>
     * 此方法可作为取消方案的一部分使用。
     * 它可能无法删除在放入内部队列之前已转换为其他形式的任务。
     * 例如，使用submit()输入的任务可能会转换为保持Future状态。 然而，在这种情况下，
     * 可以使用方法purge()删除已取消的期货。
     *
     * @param task the task to remove
     * @return {@code true} if the task was removed
     */
    public boolean remove(Runnable task) {
        boolean removed = workQueue.remove(task);
        // In case SHUTDOWN and now empty 万一关机，现在空了
        tryTerminate();
        return removed;
    }

    /**
     * Tries to remove from the work queue all {@link Future} tasks that have been cancelled.
     * This method can be useful as a storage reclamation operation, that has no other impact on functionality.
     * Cancelled tasks are never executed, but may accumulate in work queues until worker threads can actively
     * remove them. Invoking this method instead tries to remove them now.
     * However, this method may fail to remove tasks in the presence of interference by other threads.
     * <p>
     * 尝试从工作队列中删除所有已取消的Future任务。
     * 此方法可用于存储回收操作，对功能没有其他影响。取消的任务永远不会执行，但可能会累积在工作队列中，直到工作线程可以主动删除它们。
     * 调用此方法将尝试立即删除它们。但是，如果存在其他线程的干扰，此方法可能无法删除任务。
     */
    public void purge() {
        final BlockingQueue<Runnable> q = workQueue;
        try {
            Iterator<Runnable> it = q.iterator();
            while (it.hasNext()) {
                Runnable r = it.next();
                if (r instanceof Future<?> && ((Future<?>) r).isCancelled()) {
                    it.remove();
                }
            }
        } catch (ConcurrentModificationException fallThrough) {
            // Take slow path if we encounter interference during traversal.
            // Make copy for traversal and call remove for cancelled entries.
            // The slow path is more likely to be O(N*N).
            for (Object r : q.toArray()) {
                if (r instanceof Future<?> && ((Future<?>) r).isCancelled()) {
                    q.remove(r);
                }
            }
        }

        tryTerminate(); // In case SHUTDOWN and now empty
    }

    // Statistics 统计数字

    /**
     * Returns the current number of threads in the pool.
     * <p>
     * 返回池中当前的线程数
     *
     * @return the number of threads
     */
    public int getPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            // Remove rare and surprising possibility of
            // isTerminated() && getPoolSize() > 0
            return runStateAtLeast(ctl.get(), TIDYING) ? 0
                    : workers.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate number of threads that are actively executing tasks.
     * <p>
     * 返回正在积极执行任务的线程的大致数目。
     *
     * @return the number of threads
     */
    public int getActiveCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            int n = 0;
            for (Worker w : workers) {
                if (w.isLocked()) {
                    ++n;
                }
            }
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the largest number of threads that have ever simultaneously been in the pool.
     * <p>
     * 返回池中同时存在的最大线程数
     *
     * @return the number of threads
     */
    public int getLargestPoolSize() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            return largestPoolSize;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate total number of tasks that have ever been scheduled for execution.
     * Because the states of tasks and threads may change dynamically during computation, the returned
     * value is only an approximation.
     * <p>
     * 返回计划执行的任务的大致总数
     * 由于任务和线程的状态在计算过程中可能会动态变化，因此返回的值只是一个近似值。
     *
     * @return the number of tasks
     */
    public long getTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers) {
                n += w.completedTasks;
                if (w.isLocked()) {
                    ++n;
                }
            }
            return n + workQueue.size();
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns the approximate total number of tasks that have completed execution.
     * Because the states of tasks and threads may change dynamically during computation,
     * the returned value is only an approximation, but one that does not ever decrease across successive calls.
     * <p>
     * 返回已完成执行的任务的大致总数。
     * 由于任务和线程的状态在计算过程中可能会动态变化，返回的值只是一个近似值，但在连续调用中不会减少。
     *
     * @return the number of tasks
     */
    public long getCompletedTaskCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            long n = completedTaskCount;
            for (Worker w : workers) {
                n += w.completedTasks;
            }
            return n;
        } finally {
            mainLock.unlock();
        }
    }

    /**
     * Returns a string identifying this pool, as well as its state,
     * including indications of run state and estimated worker and task counts.
     * <p>
     * 返回标识此池的字符串以及其状态，包括运行状态指示、估计的工作人员和任务计数。
     *
     * @return a string identifying this pool, as well as its state
     */
    @Override
    public String toString() {
        long ncompleted;
        int nworkers, nactive;
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();

        try {
            ncompleted = completedTaskCount;
            nactive = 0;
            nworkers = workers.size();
            for (Worker w : workers) {
                ncompleted += w.completedTasks;
                if (w.isLocked()) {
                    ++nactive;
                }
            }
        } finally {
            mainLock.unlock();
        }
        int c = ctl.get();
        String rs = (runStateLessThan(c, SHUTDOWN) ? "Running" :
                (runStateAtLeast(c, TERMINATED) ? "Terminated" :
                        "Shutting down"));
        return super.toString() +
                "[" + rs +
                ", pool size = " + nworkers +
                ", active threads = " + nactive +
                ", queued tasks = " + workQueue.size() +
                ", completed tasks = " + ncompleted +
                "]";
    }

    // Extension hooks  延伸钩

    /**
     * Method invoked prior to executing the given Runnable in thegiven thread.
     * This method is invoked by thread {@code t} that will execute task {@code r},
     * and may be used to re-initialize ThreadLocals, or to perform logging.
     * <p>
     * 在给定线程中执行给定Runnable之前调用的方法。
     * 此方法由执行任务r的线程t调用，可用于重新初始化ThreadLocals或执行日志记录。
     * <p>
     * This implementation does nothing, but may be customized in subclasses.
     * Note: To properly nest multiple overridings, subclasses should generally invoke
     * {@code super.beforeExecute} at the end of this method.
     * <p>
     * 此实现不做任何事情，但可以在子类中进行自定义
     * 注意：为了正确嵌套多个重写，子类通常应该在这个方法的末尾调用super.beforeExecute()
     *
     * @param t the thread that will run task {@code r}
     * @param r the task that will be executed
     */
    protected void beforeExecute(Thread t, Runnable r) {
    }

    /**
     * Method invoked upon completion of execution of the given Runnable.
     * This method is invoked by the thread that executed the task.
     * If non-null,the Throwable is the uncaught {@code RuntimeException} or {@code Error}
     * that caused execution to terminate abruptly.
     * <p>
     * 在完成给定Runnable的执行时调用的方法。此方法由执行任务的线程调用。
     * 如果非null，Throwable是未捕获的RuntimeException或Error导致执行突然终止。
     * <p>
     * This implementation does nothing, but may be customized in subclasses.
     * Note: To properly nest multiple overridings, subclasses should generally invoke
     * {@code super.afterExecute} at the beginning of this method.
     * <p>
     * 此实现不执行任何操作，但可以在子类中自定义。
     * 注意：为了正确嵌套多个重写，子类通常应该在这个方法的开头调用 super.afterExecute()
     * <p>
     * <b>Note:</b> When actions are enclosed in tasks (such as {@link FutureTask})
     * either explicitly or via methods such as {@code submit},
     * these task objects catch and maintain computational exceptions,
     * and so they do not cause abrupt termination,
     * and the internal exceptions are <em>not</em> passed to this method.
     * If you would like to trap both kinds of failures in this method,
     * you can further probe for such cases, as in this sample subclass that prints either the direct cause
     * or the underlying exception if a task has been aborted:
     * <p>
     * 当动作被包含在任务中时（例如FutureTask）或者显式地或者通过submit()等方法，
     * 这些任务对象的捕获并处理异常并不会导致突然终止，并且内部异常不会传递给此方法。
     * 如果您想在此方法中捕获这两种失败，您可以进一步探测此类情况。
     * 如在本示例子类中，如果任务已中止，则打印直接原因或底层异常：
     * <p>
     * <pre> {@code
     * class ExtendedExecutor extends ThreadPoolExecutor {
     *   // ...
     *   protected void afterExecute(Runnable r, Throwable t) {
     *     super.afterExecute(r, t);
     *     if (t == null && r instanceof Future<?>) {
     *       try {
     *         Object result = ((Future<?>) r).get();
     *       } catch (CancellationException ce) {
     *           t = ce;
     *       } catch (ExecutionException ee) {
     *           t = ee.getCause();
     *       } catch (InterruptedException ie) {
     *           Thread.currentThread().interrupt(); // ignore/reset
     *       }
     *     }
     *     if (t != null)
     *       System.out.println(t);
     *   }
     * }}</pre>
     *
     * @param r the runnable that has completed
     * @param t the exception that caused termination, or null if
     *          execution completed normally
     */
    protected void afterExecute(Runnable r, Throwable t) {
    }

    /**
     * Method invoked when the Executor has terminated. Default implementation does nothing.
     * Note: To properly nest multiple overridings, subclasses should generally invoke
     * {@code super.terminated} within this method.
     * <p>
     * 当执行器终止时调用的方法。默认实现什么都不做。
     * 注意：为了正确嵌套多个重写，子类通常应该在这个方法中调用super.terminated()。
     */
    protected void terminated() {
    }

    // Predefined MyRejectedExecutionHandlers 预定义的RejectedExecutionHandler

    /**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
    public static class CallerRunsPolicy implements MyRejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() {
        }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }

    }

    /**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class MyAbortPolicy implements MyRejectedExecutionHandler {
        /**
         * Creates an {@code AbortPolicy}.
         */
        public MyAbortPolicy() {
        }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                    " rejected from " +
                    e.toString());
        }
    }

    /**
     * A handler for rejected tasks that silently discards the
     * rejected task.
     */
    public static class MyDiscardPolicy implements MyRejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public MyDiscardPolicy() {
        }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor e) {
        }
    }

    /**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class MyDiscardOldestPolicy implements MyRejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public MyDiscardOldestPolicy() {
        }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        @Override
        public void rejectedExecution(Runnable r, MyThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }
}
